using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace WDutils
{
    /// <summary>
    /// csvDictionaryException - custom exception class for cvsDictionary entity
    /// </summary>
    public class csvDictionaryException : Exception
    {
        /// <summary>
        /// Constructor
        /// </summary>
        public csvDictionaryException():base()
        {
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="strText"></param>
        public csvDictionaryException(string strText):base(strText)
        {
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="strText"></param>
        /// <param name="innerEx"></param>
        public csvDictionaryException(string strText, Exception innerEx) : base(strText,innerEx)
        {
        }
    }

    /// <summary>
    /// csvDictionary - class for working with ictionary files in CSV format
    /// </summary>
    public class csvDictionary
    {
        /// <summary>
        /// Stores the entire dictionary as it was read from the input file
        /// </summary>
        private Dictionary<string, string> m_List;

        /// <summary>
        /// Constructor - must receive the file path to the CSV file
        /// </summary>
        /// <param name="strFilePath"></param>
        public csvDictionary(string strFilePath)
        {
            this.m_List = new Dictionary<string,string>();

            if (!File.Exists(strFilePath)) throw new FileNotFoundException("File: "+strFilePath+" not found!");

            string fileContent = File.ReadAllText(strFilePath);

            string[] arrStrings = fileContent.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            string[] arrValues = new string[2];
            for (int i = 0; i < arrStrings.Length; i++)
            {
                arrValues = arrStrings[i].Split(new Char[] { ',' });
                string strKey = arrValues[0].ToUpper().Trim();
                if (this.m_List.ContainsKey(strKey))
                    this.m_List[strKey] = arrValues[1];
                else this.m_List.Add(strKey, arrValues[1]); 
            }
        }
        /// <summary>
        /// Gets the value for the requested key
        /// </summary>
        /// <param name="strKey"></param>
        /// <returns></returns>
        public string getValue(string strKey) 
        {
            if (this.m_List.ContainsKey(strKey.ToUpper()))
            {
                return this.m_List[strKey.ToUpper()];
            }

            throw new csvDictionaryException("Unable to find any matching value for requested key:" + strKey);
        }
    }
}
